package es.bwain.xprt.action;

import java.util.Hashtable;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class Action {

	public static final String STICKY_BALLS = "xprt_sticky_balls_store";
	public static final String RESPONSE_REDIRECT = "xprt_response_redirect";
	public static final String RESPONSE_FORMAT = "xprt_response_format";
	
	private Hashtable<String, Object> balls = new Hashtable<String, Object>();
	private HttpServletRequest storedRequest;
	@SuppressWarnings("unused")
	private HttpServletResponse storedResponse;
	
	public void init(HttpServletRequest request, HttpServletResponse response) {
		this.storedRequest = request;
		this.storedResponse = response;
		if (this.getStickyBalls() == null) {
			this.initStickyBalls();
		}
	}
	
	public abstract void execute(HttpServletRequest request, HttpServletResponse response);
	
	public void putBall(String key, Object ball) {
		this.balls.put(key, ball);
	}
	
	public void removeBall(String key) {
		this.balls.remove(key);
	}
	
	public void putStickyBall(String key, Object ball) {
		this.getStickyBalls().put(key, ball);
	}
	
	public void removeStickyBall(String key) {
		this.getStickyBalls().remove(key);
	}
	
	public Hashtable<String, Object> getBalls() {
		return this.balls;
	}
	
	public Hashtable<String, Object> getAllBalls() {
		Hashtable<String, Object> allBalls = this.balls;
		Hashtable<String, Object> stickyBalls = this.getStickyBalls();
		Iterator<String> iter = stickyBalls.keySet().iterator();
		while (iter.hasNext()) {
			String key = iter.next();
			Object value = stickyBalls.get(key);
			allBalls.put(key, value);
		}
		return allBalls;
	}
	
	@SuppressWarnings("unchecked")
	public Hashtable<String, Object> getStickyBalls() {
		return (Hashtable<String, Object>) this.storedRequest.getSession().getAttribute(STICKY_BALLS);
	}
	
	private void initStickyBalls() {
		this.storedRequest.getSession().setAttribute(STICKY_BALLS, new Hashtable<String, Object>());
	}
	
	public void setRedirectTo(String destination) {
		this.storedRequest.setAttribute(RESPONSE_REDIRECT, destination);
	}
	
	public void setResponseFormat(ResponseFormat responseFormat) {
		this.storedRequest.setAttribute(RESPONSE_FORMAT, responseFormat);
	}
	
}
